package com.lsh.payment.core.service.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.payment.core.model.payenum.RefundStatus;
import com.lsh.payment.core.model.payenum.RefundTaskStatus;
import com.lsh.payment.core.model.refund.PayRefund;
import com.lsh.payment.core.model.refund.RefundTask;
import com.lsh.payment.core.service.refund.IRefundTaskService;
import com.lsh.payment.core.util.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: lsh-payment
 *
 * @author peter
 * @date 18/6/6
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service
@Slf4j
public class RefundNotifyProxy {

    @Autowired
    private IRefundTaskService refundTaskService;


    /**
     * 处理通知业务方
     *
     * @param payRefund  退款记录
     * @param refundTask 通知任务
     */
    public Boolean dealRefundNotify(PayRefund payRefund, RefundTask refundTask) {

        if (payRefund == null || refundTask == null) {
            return false;
        }

        boolean notifyFlag = false;
        if (this.sendRefundNotify(payRefund, refundTask)) {
            refundTask.setStatus(RefundTaskStatus.TASK_SUCCESS.getValue());
            notifyFlag = true;
        } else {
            refundTask.setStatus(RefundTaskStatus.TASK_FAIL.getValue());
        }

        return refundTaskService.updateByRefIdAndType(refundTask) > 0 && notifyFlag;
    }


    /**
     * 发送通知
     *
     * @param payRefund  退款记录
     * @param refundTask 通知任务
     * @return 返回结果
     */
    private boolean sendRefundNotify(PayRefund payRefund, RefundTask refundTask) {
        String prefix = payRefund.getPaymentRefundNo() + " -【退款回调业务方】[sendRefundNotify] ";
        log.info("【{}】 start", prefix);

        boolean notifySuccessFlag = false;
        Map<String, Object> notifyRequestMap = new HashMap<>(5);

        notifyRequestMap.put("payment_refund_no", payRefund.getPaymentRefundNo());
        notifyRequestMap.put("refund_trade_id", payRefund.getRefundTradeId());

        if (RefundStatus.REFUND_SUCCESS.getValue() == payRefund.getRefundStatus()) {
            notifyRequestMap.put("refund_flag", "SUCCESS");
        } else {
            notifyRequestMap.put("refund_flag", "FAIL");
        }
        payRefund.init();
        notifyRequestMap.put("notify_ext", payRefund.getNotify_ext());
//        notifyRequestMap.put("refund_msg", payRefund.getExt());
        JSONObject extJson = JSON.parseObject(payRefund.getExt());
//        String errCode = extJson.getString("err_code");
        String errCodeDes = extJson.getString("err_code_des");
        if (RefundStatus.REFUND_CLOSE.getValue() <= payRefund.getRefundStatus()) {
            if (StringUtils.isNotBlank(errCodeDes)) {
                notifyRequestMap.put("error_reason", errCodeDes);
            } else {
                notifyRequestMap.put("error_reason", "账户余额不足或退款已关闭,请联系技术人员确认。");
            }
        }


        log.info("【{}】 refund notifyRequestMap is {}", prefix, JSON.toJSONString(notifyRequestMap));
        try {
            String notifyRefundRequestJson = JSON.toJSONString(notifyRequestMap);
            log.info("refund JOP 通知业务方 : " + notifyRefundRequestJson);
            Map<String, String> headMap = new HashMap<>();
            headMap.put("venderId",payRefund.getVenderId()+ "");
            String notifyResponse = HttpClientUtils.doPostBody(payRefund.getRefundNotifyUrl(), notifyRefundRequestJson,headMap);

            log.info("【asyn refund notify response】 is : [" + notifyResponse + "]");
            String returnCode = null;
            if (StringUtils.isNotBlank(notifyResponse)) {
                JSONObject notifyResponseJson = JSONObject.parseObject(notifyResponse);
                if (notifyResponseJson != null && notifyResponseJson.getJSONObject("content") != null) {
                    returnCode = notifyResponseJson.getJSONObject("content").getString("return_code");
                }
            }

            if (StringUtils.isNotBlank(returnCode) && returnCode.equals("SUCCESS")) {
                notifySuccessFlag = true;
            } else {
                log.info("【asyn refund notify fail : tradeId is】 : " + refundTask.getRefId() + " ,return_msg is : " + notifyResponse);
            }
        } catch (Exception e) {

            log.error("【退款通知业务方失败】:" + refundTask.getRefId(), e);
        }

        return notifySuccessFlag;
    }

}
